

const HORIZNTAL_SIZE = 30;
const VERTICAL_SIZE = 28;

class Gobang {
    constructor(){
        this.HORIZNTAL_SIZE =HORIZNTAL_SIZE;
        this.VERTICAL_SIZE =VERTICAL_SIZE;
        this.players = [];  // 玩家列表
        this.checkerBoard = []; //棋盘
        this.colorList = ['white','black']; // 棋子颜色
        this.gaming = false; // 棋子状态
        this.trun = 'black'; //当前落子颜色
    }
    // 创建玩家
    createPlayer(socket){
      let playerCount = this.players.length;
      if(playerCount>=2) return false;
      let player = {
          socket,
          color:this.colorList.pop()
      };
      this.players.push(player);
      socket.player = player;
      return true;
    }

    // 初始化
    init(){
        for (let i=-5;i<this.HORIZNTAL_SIZE+5;i++){
            this.checkerBoard[i]=[];
            for (let j=-5;j<this.VERTICAL_SIZE+5;j++){
                this.checkerBoard[i][j]={
                    state:0,
                    type:true
                }
            }
        }
        this.gaming = true
    }


    // 获取当前玩家的数量

    getPlayerNum(){
        return this.players.length;
    }
    // 离开房间
    leftGame(socket){
      if(!socket.player) return;
      for(let i = 0;i<this.players.length;i++){
          if(this.players[i].color === socket.player.color ){
              this.colorList.push(this.players[i].color);
              this.players.splice(i,1);
              break
          }
      }
    }
    // 反转颜色
    toggleTurn(){
        this.trun = (this.trun === 'black'?'white':'black')
    }
   // 放置旗子
    putChess(x,y){
      this.checkerBoard[x][y].state = true;
      this.checkerBoard[x][y].type = this.trun;
      this.toggleTurn();
    }


     gameover(x,y) {
        // 从左上角到右下角是否满足条件
        return this.checkAllDirectionClass(x,y);
    }
    //判断一个方向上是否满足
    checkAllDirectionClass(x,y) {
        if(this.checkOnlineChess(x-5,y-5,1,1,this.checkerBoard[x][y].type)) return true;
        if(this.checkOnlineChess(x,y-5,0,1,this.checkerBoard[x][y].type)) return true;
        if(this.checkOnlineChess(x+5,y-5,-1,1,this.checkerBoard[x][y].type)) return true;
        if(this.checkOnlineChess(x-5,y,1,0,this.checkerBoard[x][y].type)) return true;
        return false
    }

    checkOnlineChess(tpx,tpy,xPlus,yPlus,type) {
        let count = 0;
        for(let i =0;i<10;i++){
            if(this.checkerBoard[tpx][tpy].type === type && this.checkerBoard[tpx][tpy].state !==0 ){
                count ++;
                if(count >= 5) return true;
            }else{
                count = 0;
            }
            tpx += xPlus;
            tpy += yPlus
        }
    }
}

module.exports = Gobang;